<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item prop="storageId">
        <el-select v-model="queryParams.storageId" placeholder="请选择仓库" clearable>
          <el-option v-for="item in storages" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item prop="categoryId">
        <el-cascader :options="categories" :props="{ checkStrictly: true ,value:'id'}" placeholder="请选择类目" clearable filterable
          @change="onSelectCategory"/>
      </el-form-item>
      <el-form-item prop="keyword">
        <el-input v-model="queryParams.keyword" clearable placeholder="请输入商品名称"/>
      </el-form-item>
      <el-form-item prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择销售状态" clearable>
          <el-option v-for="dict in dict.type.sale_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini"
          @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="mini"
          @click="resetQuery">重置</el-button>
        <!--<el-button v-hasPermi="['storage:goods:add']" type="primary" icon="el-icon-plus" size="mini"
          @click="handleAdd">新增</el-button>-->
        <!--<el-button v-hasPermi="['storage:goods:export']" type="warning" icon="el-icon-download" size="mini"
          @click="handleExport">导出</el-button>-->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="storageGoodsList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" width="80" align="center">
        <template slot-scope="{$index}">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
        </template>
      </el-table-column>
      <!-- <el-table-column v-if="true" label="主键" align="center" prop="id" /> -->
      <!-- <el-table-column label="仓库ID" align="left" header-align="center" prop="storageId" />-->
      <!-- <el-table-column label="仓库名称" align="left" header-align="center" prop="storageName" />-->
      <!-- <el-table-column label="商品ID" align="left" header-align="center" prop="productId" />-->
      <el-table-column label="商品名称" align="left" header-align="center" prop="productName" />
      <!-- <el-table-column label="商品规格ID" align="left" header-align="center" prop="productAttrId" />-->
      <el-table-column label="商品规格" align="left" header-align="center" prop="productAttrName" />
      <!-- <el-table-column label="商品类目ID" align="left" header-align="center" prop="categoryId" />-->
      <el-table-column label="商品类目" align="left" header-align="center" prop="categoryName" />
      <!-- <el-table-column label="商品条码" align="left" header-align="center" prop="barCode" />-->
      <el-table-column label="销售状态" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sale_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="库存可售量" align="center" prop="stock" />
      <el-table-column label="单位" align="center" prop="unitName" />
      <el-table-column label="原价" align="center" prop="originalPrice" />
      <el-table-column label="当前售价" align="center">
        <template slot-scope="{row}">
          <el-input v-if="editMode[row.id]" v-model="row.price" clearable @blur="updatePrice(row)" />
          <el-button v-else type="text" @click="editMode[row.id]=true">
            {{ row.price }}
          </el-button>
        </template>
      </el-table-column>
      <!--<el-table-column label="折扣" align="center">
        <template slot-scope="{row}">
          {{ getDiscount(row) }}
        </template>
      </el-table-column>-->
      <el-table-column label="入库时间" align="center" prop="createTime" width="150" />
      <el-table-column label="修改时间" align="center" prop="updateTime" width="150" />
      <el-table-column label="操作" align="center" class-name="small-padding" width="300">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status===0" v-hasPermi="['storage:goods:edit']" size="mini" type="primary" icon="el-icon-edit"
            @click="updateStatus(scope.row,1)">上架</el-button>
          <el-button v-else v-hasPermi="['storage:goods:edit']" size="mini" type="danger" icon="el-icon-edit"
            @click="updateStatus(scope.row,0)">下架</el-button>
          <el-button v-hasPermi="['storage:goods:edit']" size="mini" type="success" icon="el-icon-edit"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-if="scope.row.status===0" v-hasPermi="['storage:goods:remove']" size="mini" type="danger" icon="el-icon-delete"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--<el-form-item label="仓库ID" prop="storageId">
          <el-input v-model="form.storageId" placeholder="请输入仓库ID" />
        </el-form-item>-->
        <!--<el-form-item label="商品ID" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入商品ID" />
        </el-form-item>-->
        <!--<el-form-item label="商品规格ID" prop="productAttrId">
          <el-input v-model="form.productAttrId" placeholder="请输入商品规格ID" />
        </el-form-item>-->
        <!--<el-form-item label="分类ID" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入商品分类ID" />
        </el-form-item>-->
        <el-table-column label="销售状态" align="center">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sale_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-form-item label="库存可售量" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存可售量" />
        </el-form-item>
        <el-form-item label="销售量" prop="sales">
          <el-input v-model="form.sales" placeholder="请输入销售量" />
        </el-form-item>
        <el-form-item label="冻结库存" prop="frezzStock">
          <el-input v-model="form.frezzStock" placeholder="请输入冻结库存" />
        </el-form-item>
        <el-form-item label="当前售价" prop="price">
          <el-input v-model="form.price" placeholder="请输入当前售价" />
        </el-form-item>
        <el-form-item label="预警数量" prop="warningNum">
          <el-input v-model="form.warningNum" placeholder="请输入预警数量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStorageGoods, getStorageGoods, addStorageGoods, updateStorageGoods, delStorageGoods, updateStorageGoodsPrice, updateStorageGoodsStatus } from '@/api/storage/goods'
import { listAllStorage } from '@/api/storage/storage'
import { listStoreCategoryTree } from '@/api/product/storeCategory'
import NP from 'number-precision'

export default {
  name: 'StorageGoods',
  dicts: ['sale_status'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库商品表格数据
      storageGoodsList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storageId: undefined,
        productId: undefined,
        productAttrId: undefined,
        categoryId: undefined,
        status: undefined,
        keyword: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: { },
      storages: [],
      categories: [],
      editMode: {}
    }
  },
  created() {
    this.getList()
    this.listAllStorage()
    this.listStoreCategoryTree()
  },
  methods: {
    listAllStorage() {
      listAllStorage().then(({ data }) => {
        this.storages = data
      })
    },
    listStoreCategoryTree() {
      listStoreCategoryTree().then(({ data }) => {
        this.categories = data.content
      })
    },
    /** 查询仓库商品列表 */
    getList() {
      this.loading = true
      this.editMode = {}
      listStorageGoods(this.queryParams).then(response => {
        this.storageGoodsList = response.rows
        this.total = response.total
        this.loading = false
        response.rows.forEach(({ id }) => {
          this.$set(this.editMode, id, false)
        })
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        storageId: undefined,
        storageName: undefined,
        productId: undefined,
        productName: undefined,
        productAttrId: undefined,
        productAttrName: undefined,
        categoryId: undefined,
        categoryName: undefined,
        status: undefined,
        stock: undefined,
        sales: undefined,
        frezzStock: undefined,
        price: undefined,
        warningNum: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加仓库商品'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true
      this.reset()
      const id = row.id
      getStorageGoods(id).then(response => {
        this.loading = false
        this.form = response.data
        this.open = true
        this.title = '修改仓库商品'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.id != null) {
            updateStorageGoods(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
               this.getList()
            }).finally(() => {
               this.buttonLoading = false
            })
          } else {
            addStorageGoods(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            }).finally(() => {
               this.buttonLoading = false
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认删除？').then(() => {
        this.loading = true
        return delStorageGoods(id)
      }).then(() => {
        this.loading = false
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      }).finally(() => {
        this.loading = false
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('storage/goods/export', {
        ...this.queryParams
      }, `storage_goods_${new Date().getTime()}.xlsx`)
    },
    onSelectCategory(value) {
      this.queryParams.categoryId = value[value.length - 1]
    },
    getDiscount(row) {
      const { price, originalPrice } = row
      if (Number(originalPrice) === 0) {
        return '0.00'
      }
      return (NP.divide(NP.times(price, 10), originalPrice)).toFixed(2)
    },
    updatePrice(row) {
      const { id, price } = row
      updateStorageGoodsPrice({ id, price }).then(() => {
        this.editMode[id] = false
      })
    },
    updateStatus(row, status) {
      this.$modal.confirm(status === 1 ? '是否将此商品上架' : '是否将此商品下架').then(() => {
        this.loading = true
        return updateStorageGoodsStatus({ id: row.id, status })
      }).then(() => {
        this.loading = false
        this.getList()
      }).catch(() => {
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>
